package cn.edu.cug.cs.gtl.plugins.device.actions;

import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.apis.ui.datake.devicetree.DeviceTree;
import cn.edu.cug.cs.gtl.apis.ui.tree.TreeNodeData;
import cn.edu.cug.cs.gtl.protos.StorageCluster;
import cn.edu.cug.cs.gtl.utils.impl.DataDeviceManagerImpl;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.event.ActionEvent;
import java.util.Locale;
import java.util.ResourceBundle;

public class DeleteStorageClusterAction extends AbstractAction {
    @Override
    public void initialize(AbstractApplication theApp) {
        ResourceBundle resourceBundle= ResourceBundle.getBundle("device-resource", Locale.getDefault());
        name=resourceBundle.getString("popupmenu.device.tree.remove_storage_cluster");
        menuItem.setText(name);

        this.theApp = theApp;
        menuItem.addActionListener(this);
        ((DeviceTree) theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent()).getStorageClusterNodePopupMenu().add(menuItem);
        ((DeviceTree) theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent()).getStorageChildNodePopupMenu().add(menuItem);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //获取当前选中的集群节点数据
        DeviceTree tree = (DeviceTree) theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent();
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        TreeNodeData treeNodeData = (TreeNodeData) selectedNode.getUserObject();
        Object refObject = treeNodeData.getRefObject();

        //如果是存储集群节点，弹出确认删除对话框
        if (refObject instanceof StorageCluster) {
            StorageCluster storageCluster = (StorageCluster) refObject;
            int option = JOptionPane.showConfirmDialog(theApp.getMainFrame(), "确认删除？", "确认", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                //删除节点
                DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
                treeModel.removeNodeFromParent(selectedNode);

                // 删除数据库中相应数据
                DataDeviceManagerImpl dataDeviceManager=new DataDeviceManagerImpl();
                dataDeviceManager.removeStorageCluster(storageCluster.getName());

            }
        }
    }
}
